<template>
  <nav class="navbar navbar-expand-lg navbar-light bg-light" v-if="$store.getters.getUser">
    <div class="container">
      <router-link class="navbar-brand" to="/">
        <i class="far fa-gem"></i>
      </router-link>
      <button
        class="navbar-toggler"
        type="button"
        data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <router-link class="nav-link" to="/">
              Home
              <span class="sr-only">(current)</span>
            </router-link>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
        </ul>
        <ul class="navbar-nav ml-auto">
          <li class="nav-item dropdown shopCart">
            <a class="nav-link" >
              <i class="fa fa-shopping-cart pr-1"></i>购物车
              <span v-if="calcShopCardGoods(true)"  class="badge badge-pill badge-info" style="vertical-align: super;padding-left:.4rem;padding-right:.35rem">
                {{calcShopCardGoods(true)}}
              </span>
            </a>
            <div class="dropdown-menu" v-if="calcShopCardGoods(true)">
              <a class="dropdown-item" v-for="(item,index) in calcShopCardGoods(false)" :key="index" >
                {{item.D_title.substring(0,20)}}
                <span class="badge badge-secondary" style="vertical-align: text-bottom;">{{item.addShopCardNum}}</span>
              </a>
              <div class="dropdown-divider"></div>
              <div class="dropdown-item">
                <router-link to="/shopcart" class="btn btn-danger btn-sm" style="margin-left: calc(80%);">去结算</router-link>
              </div>
            </div>
            <div class="dropdown-menu" v-else>
              <a class="dropdown-item">当前购物车空空如也，快去购点物吧！</a>
              <div class="dropdown-divider"></div>
              <div class="dropdown-item">
                <router-link to="/" class="btn btn-danger btn-sm" style="margin-left: calc(80%);">去购物</router-link>
              </div>
            </div>            
          </li>
          <li class="nav-item" v-if="curUserInfo.id==undefined">
            <router-link class="nav-link" to="/login">登陆</router-link>
          </li>
          <li class="nav-item" v-if="curUserInfo.id==undefined">
            <router-link class="nav-link" to="/register">注册</router-link>
          </li>
          <li class="nav-item dropdown" v-if="curUserInfo.id!=undefined">
            <a
              class="nav-link dropdown-toggle"
              href="#"
              id="navbarDropdown"
              role="button"
              data-toggle="dropdown"
              aria-haspopup="true"
              aria-expanded="false"
            >
              <i class="fas fa-user"></i>
              {{curUserInfo.username}}
            </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <!-- <router-link class="dropdown-item" to="#" v-if="curUserInfo.role=='user'">用户中心</router-link> -->
              
              <router-link class="dropdown-item" :to="'/admin?id='+curUserInfo.id" v-if="curUserInfo.id==1">管理中心</router-link>
              <a class="dropdown-item" v-else>余额：{{calcAcoountMoney}} 元</a>
              <div class="dropdown-divider"></div>
              <div class="dropdown-item">
                <span class="btn btn-danger btn-sm" style="margin-left: calc(50%);" @click="quitUser(curUserInfo.id,curUserInfo.username)">退出</span>
              </div>  
            </div>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</template>

<script>
export default {
  data() {
    return {
      curUserInfo: {},
    };
  },
  computed:{
    calcShopCardGoods(getGoodsNum) {
      return function(getGoodsNum){
        if(this.$store.getters.getShopCartGood){
            if (getGoodsNum) return this.$store.getters.getShopCartGood.length;
            else return this.$store.getters.getShopCartGood;
        }
      }
    },
    calcAcoountMoney(){
      for(let item of this.$store.getters.getUser){
        if(item.isLogin){
          return item.accountMoney;
        }
      }
    }  
  },
  watch:{
    '$store.getters.getUser': function (newVal,oldVal) {
      if(this.curUserInfo.id){
        //this.addLocalShopCardData();
        this.$store.commit("changeLoginStatus",this.curUserInfo["id"]);
      }
    },
    // curUserInfo(newVal,oldVal){
    //   if(newVal){
    //     console.log("newVal");
    //   }
    // }   
  },
  created() {
    this.getUserInfo(); 
  },
  mounted(){
    this.$store.commit("addIsCreate");
    this.$store.commit("editMoneyAlreadyCalc");
    if(this.$store.getters.getIsCreate==1){
      this.addLocalShopCardData();
      this.addLocalUser();  
    }
  },
  methods: {
    getUserInfo() {
      let userInfo = document.cookie.split(";");
      for (let value of userInfo) {
        if (value.split("=")[0].trim() == "id") {
          this.curUserInfo["id"] = value.split("=")[1];
        }
        if (value.split("=")[0].trim() == "username") {
          this.curUserInfo["username"] = decodeURIComponent(
            value.split("=")[1]
          );
        }
      }

      //this.addLocalShopCardData();
     //this.$store.commit("changeLoginStatus",this.curUserInfo["id"]);   
    },
    quitUser(userId, userName) {
      this.$store.commit("addIsCreate",0);
      this.quitSaveCurShopCardData();
      this.curUserInfo = {};
      this.deleteCookie(userId, userName, -1);
      this.$store.commit("changeLoginStatus");
      this.$store.commit("clearShopCart");
      this.$router.push('/login');
    },
    deleteCookie(userId, userName, expires) {
      let Days = expires;
      let exp = new Date();
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
      document.cookie = `id=${userId};expires=${exp.toGMTString()}`;
      document.cookie = `username=${encodeURI(
        userName
      )};expires=${exp.toGMTString()}`;
    },
    addLocalShopCardData(){

      if(localStorage.getItem('newUserOrder')!=null){
        let readyUserOrderDate=JSON.parse(localStorage.getItem('newUserOrder'));
        let accountMoney=0;
        for(let item of readyUserOrderDate){
            if(item.userId==this.curUserInfo.id){
              accountMoney+=item.goodsSum;
            }
            for(let item2 of item.purchaseGoods){
              if(item.userId==this.curUserInfo.id && !item.payStatus){
                this.$store.commit('addShopCard',item2);
              }
          } 
        }
        if(this.$store.getters.getMoneyAlreadyCalc==1) this.$store.dispatch("awaitChangeAccountMoney",accountMoney);
      }
      if(localStorage.getItem('newShopCart')!=null){
        let readyShopCart=JSON.parse(localStorage.getItem('newShopCart'));
        for(let item of readyShopCart){
          if(item.userId==this.curUserInfo.id){
            for(let item2 of item.shopCard){  
              this.$store.commit('addShopCard',item2);
            }
          }
        }
      }
    },
    quitSaveCurShopCardData(){
        let curShopCard = this.calcShopCardGoods(false);
        
        if(curShopCard.length==0){
          let LocalShopCardData =JSON.parse(localStorage.getItem('newShopCart'));
          for(let item of LocalShopCardData){
              if(item.userId==this.curUserInfo.id){
                  item.shopCard=[];
                  break;
              }
          }
          localStorage.setItem('newShopCart',JSON.stringify(LocalShopCardData));             
          return;
        }

        if(localStorage.getItem('newShopCart') != null){
            let LocalShopCardData =JSON.parse(localStorage.getItem('newShopCart'));
            let find=false;
            for(let item of curShopCard){
              for(let item2 of LocalShopCardData){
                if(item2.userId==this.curUserInfo.id){
                    item2.shopCard=[...curShopCard];
                    find=true;
                    break;
                }
              }
              break;
            }
            if(find){
              localStorage.setItem('newShopCart',JSON.stringify(LocalShopCardData));
            }else{
              LocalShopCardData.push({userId:this.curUserInfo.id,shopCard:[...curShopCard]});
              localStorage.setItem('newShopCart',JSON.stringify(LocalShopCardData));
            }
                    
        }else{
          let newShopCard=[{userId:this.curUserInfo.id,shopCard:[]}];
          for(let item of curShopCard){
            newShopCard[0].shopCard.push(item);
          }
          localStorage.setItem('newShopCart',JSON.stringify(newShopCard));
        }
    },
    addLocalUser(){
      if(localStorage.getItem('newUser') != null){
          let LocalUserData =JSON.parse(localStorage.getItem('newUser'));
          for(let item of LocalUserData){
            this.$store.commit("addUser",item);
          }
      }      
    },



  }
};
</script>

<style scoped>
.shopCart:hover .dropdown-menu {
  display: block;
}
a:hover{
  cursor: pointer;
}
.dropdown-menu{
  min-width: 7rem;
  text-align: center;
}
</style>

